import { AuthActionTypes, LOGIN_TYPE, LOGOUT } from './types'
import { Dispatch } from 'redux'
import { post, get } from '../../ajax/axios'
import { Api, Admin } from '../../ajax/api'

/**
 * 获取CSRF
 */
export function getCsrf() {
  get(Api.csrf)
}

/**
 * 登录
 * @param user 用户名
 * @param pass 密码
 * @param code 验证码
 */
export function loginAction(user: string, pass: string, code: string): (dispatch: Dispatch<AuthActionTypes>) => Promise<AuthActionTypes> {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    return new Promise((res, rej) => {
      post(Api.user.login, {
        user, pass, code
      }).then((data: any) => {
        dispatch({
          type: LOGIN_TYPE,
          value: data
        })
        res()
      }).catch((err) => {
        rej(err)
      })
    })
  }
}

/**
 * session 登录
 */
export function sessionLoginAction(): (dispatch: Dispatch<AuthActionTypes>) => Promise<AuthActionTypes> {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    return new Promise((res, rej) => {
      get(Api.user.sessionLogin).then((data: any) => {
        if(data) {
          dispatch({
            type: LOGIN_TYPE,
            value: data
          })
        }
        res(data)
      }).catch((err) => {
        rej(err)
      })
    })
  }
}

export function logout(): (dispatch: Dispatch<AuthActionTypes>) => Promise<AuthActionTypes> {
  return (dispatch: Dispatch<AuthActionTypes>) => {
    return new Promise((res, rej) => {
      get(Admin.auth.user.logout).then((data: any) => {
        dispatch({
          type: LOGOUT,
        })
        res(data)
      }).catch((err) => {
        rej(err)
      })
    })
  }
}

